package cn.da.shuai.cool.finance.service.impl;

import cn.da.shuai.cool.common.expection.CoolServiceException;
import cn.da.shuai.cool.finance.mapper.CoolFinancialAnalyticsMapper;
import cn.da.shuai.cool.finance.model.CoolFinancialAnalytics;
import cn.da.shuai.cool.finance.service.ICoolFinancialAnalyticsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CoolFinancialAnalyticsServiceImpl extends ServiceImpl<CoolFinancialAnalyticsMapper, CoolFinancialAnalytics>
        implements ICoolFinancialAnalyticsService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateMonthlyAnalytics(Integer fiscalYear, Integer fiscalMonth) {
        // 验证参数
        validateFiscalPeriod(fiscalYear, fiscalMonth);

        // 获取所有部门的财务数据并生成分析
        List<Long> departmentIds = getDepartmentIds(); // 假设有方法获取所有部门ID
        for (Long departmentId : departmentIds) {
            CoolFinancialAnalytics analytics = new CoolFinancialAnalytics();
            analytics.setFiscalYear(fiscalYear)
                    .setFiscalMonth(fiscalMonth)
                    .setDepartmentId(departmentId)
                    .setAnalysisDate(LocalDate.now());

            // 计算各项财务指标
            calculateLiquidityRatios(analytics);
            calculateProfitabilityRatios(analytics);
            calculateEfficiencyRatios(analytics);
            calculateBudgetMetrics(analytics);

            // 保存或更新分析结果
            saveOrUpdateAnalytics(analytics);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateQuarterlyAnalytics(Integer fiscalYear, Integer fiscalQuarter) {
        if (fiscalQuarter < 1 || fiscalQuarter > 4) {
            throw new CoolServiceException("财政季度必须在1-4之间");
        }

        // 计算该季度包含的月份
        int startMonth = (fiscalQuarter - 1) * 3 + 1;
        int endMonth = fiscalQuarter * 3;

        // 汇总季度数据
        for (int month = startMonth; month <= endMonth; month++) {
            generateMonthlyAnalytics(fiscalYear, month);
        }

        // 生成季度汇总报告
        aggregateQuarterlyData(fiscalYear, fiscalQuarter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateYearlyAnalytics(Integer fiscalYear) {
        // 生成所有月度分析
        for (int month = 1; month <= 12; month++) {
            generateMonthlyAnalytics(fiscalYear, month);
        }

        // 生成年度汇总报告
        aggregateYearlyData(fiscalYear);
    }

    @Override
    public List<CoolFinancialAnalytics> getAnalyticsByDepartment(Long departmentId, Integer fiscalYear) {
        LambdaQueryWrapper<CoolFinancialAnalytics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoolFinancialAnalytics::getDepartmentId, departmentId)
                .eq(CoolFinancialAnalytics::getFiscalYear, fiscalYear)
                .orderByAsc(CoolFinancialAnalytics::getFiscalMonth);

        return this.list(queryWrapper);
    }

    @Override
    public List<CoolFinancialAnalytics> getAnalyticsByPeriod(Integer fiscalYear, Integer fiscalMonth) {
        return baseMapper.findByFiscalYearAndMonth(fiscalYear, fiscalMonth);
    }

    @Override
    public Map<String, Object> getDashboardMetrics(Integer fiscalYear) {
        Map<String, Object> dashboard = new HashMap<>();

        // 获取当年所有分析数据
        List<CoolFinancialAnalytics> yearlyAnalytics = getYearlyAnalytics(fiscalYear);

        // 计算关键指标平均值
        dashboard.put("averageCurrentRatio", calculateAverageMetric(yearlyAnalytics, CoolFinancialAnalytics::getCurrentRatio));
        dashboard.put("averageQuickRatio", calculateAverageMetric(yearlyAnalytics, CoolFinancialAnalytics::getQuickRatio));
        dashboard.put("averageGrossMargin", calculateAverageMetric(yearlyAnalytics, CoolFinancialAnalytics::getGrossMargin));
        dashboard.put("averageNetProfitMargin", calculateAverageMetric(yearlyAnalytics, CoolFinancialAnalytics::getNetProfitMargin));
        dashboard.put("averageROE", calculateAverageMetric(yearlyAnalytics, CoolFinancialAnalytics::getReturnOnEquity));
        dashboard.put("averageBudgetExecutionRate", calculateAverageMetric(yearlyAnalytics, CoolFinancialAnalytics::getBudgetExecutionRate));

        // 添加趋势数据
        dashboard.put("monthlyTrends", getMonthlyTrends(yearlyAnalytics));

        return dashboard;
    }

    @Override
    public Map<String, Object> getTrendAnalysis(Integer fiscalYear, String metricName) {
        Map<String, Object> trends = new HashMap<>();

        // 获取指定年份的月度数据
        List<CoolFinancialAnalytics> analytics = getYearlyAnalytics(fiscalYear);

        // 按月份分组并计算平均值
        Map<Integer, BigDecimal> monthlyAverages = analytics.stream()
                .collect(Collectors.groupingBy(
                        CoolFinancialAnalytics::getFiscalMonth,
                        Collectors.mapping(a -> getMetricValue(a, metricName),
                                Collectors.collectingAndThen(
                                        Collectors.toList(),
                                        this::calculateAverage))));

        trends.put("monthlyData", monthlyAverages);

        // 计算同比增长
        if (fiscalYear > 2000) {  // 假设2000年为最早数据
            List<CoolFinancialAnalytics> lastYearAnalytics = getYearlyAnalytics(fiscalYear - 1);
            Map<Integer, BigDecimal> lastYearAverages = lastYearAnalytics.stream()
                    .collect(Collectors.groupingBy(
                            CoolFinancialAnalytics::getFiscalMonth,
                            Collectors.mapping(a -> getMetricValue(a, metricName),
                                    Collectors.collectingAndThen(
                                            Collectors.toList(),
                                            this::calculateAverage))));

            Map<Integer, BigDecimal> yearOverYearGrowth = new HashMap<>();
            monthlyAverages.forEach((month, value) -> {
                BigDecimal lastYear = lastYearAverages.get(month);
                if (lastYear != null && lastYear.compareTo(BigDecimal.ZERO) != 0) {
                    BigDecimal growth = value.subtract(lastYear)
                            .divide(lastYear, 4, RoundingMode.HALF_UP)
                            .multiply(new BigDecimal("100"));
                    yearOverYearGrowth.put(month, growth);
                }
            });

            trends.put("yearOverYearGrowth", yearOverYearGrowth);
        }

        return trends;
    }

    // 私有辅助方法
    private void validateFiscalPeriod(Integer fiscalYear, Integer fiscalMonth) {
        if (fiscalYear == null || fiscalYear < 2000) {
            throw new CoolServiceException("无效的财政年度");
        }
        if (fiscalMonth == null || fiscalMonth < 1 || fiscalMonth > 12) {
            throw new CoolServiceException("无效的财政月份");
        }
    }

    private void calculateLiquidityRatios(CoolFinancialAnalytics analytics) {
        // 这里应该从资产负债表中获取实际数据
        // 示例计算方法
        analytics.setCurrentRatio(new BigDecimal("2.5"))
                .setQuickRatio(new BigDecimal("1.8"))
                .setDebtToAssetsRatio(new BigDecimal("0.4"));
    }

    private void calculateProfitabilityRatios(CoolFinancialAnalytics analytics) {
        // 从损益表中获取数据并计算
        analytics.setGrossMargin(new BigDecimal("0.35"))
                .setNetProfitMargin(new BigDecimal("0.15"))
                .setReturnOnAssets(new BigDecimal("0.12"))
                .setReturnOnEquity(new BigDecimal("0.18"));
    }

    private void calculateEfficiencyRatios(CoolFinancialAnalytics analytics) {
        // 计算运营效率指标
        analytics.setInventoryTurnover(new BigDecimal("12"))
                .setAccountsReceivableTurnover(new BigDecimal("8"))
                .setAccountsPayableTurnover(new BigDecimal("6"))
                .setCashConversionCycle(new BigDecimal("45"));
    }

    private void calculateBudgetMetrics(CoolFinancialAnalytics analytics) {
        // 计算预算相关指标
        analytics.setBudgetExecutionRate(new BigDecimal("0.95"))
                .setBudgetVariance(new BigDecimal("50000"))
                .setBudgetVariancePercentage(new BigDecimal("5"));
    }

    private void saveOrUpdateAnalytics(CoolFinancialAnalytics analytics) {
        LambdaQueryWrapper<CoolFinancialAnalytics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoolFinancialAnalytics::getFiscalYear, analytics.getFiscalYear())
                .eq(CoolFinancialAnalytics::getFiscalMonth, analytics.getFiscalMonth())
                .eq(CoolFinancialAnalytics::getDepartmentId, analytics.getDepartmentId());

        CoolFinancialAnalytics existing = this.getOne(queryWrapper);
        if (existing != null) {
            analytics.setId(existing.getId());
            this.updateById(analytics);
        } else {
            this.save(analytics);
        }
    }

    private List<CoolFinancialAnalytics> getYearlyAnalytics(Integer fiscalYear) {
        LambdaQueryWrapper<CoolFinancialAnalytics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoolFinancialAnalytics::getFiscalYear, fiscalYear)
                .orderByAsc(CoolFinancialAnalytics::getFiscalMonth);
        return this.list(queryWrapper);
    }

    private BigDecimal calculateAverageMetric(List<CoolFinancialAnalytics> analytics,
            java.util.function.Function<CoolFinancialAnalytics, BigDecimal> metricGetter) {
        return analytics.stream()
                .map(metricGetter)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(new BigDecimal(analytics.size()), 2, RoundingMode.HALF_UP);
    }

    private Map<String, List<BigDecimal>> getMonthlyTrends(List<CoolFinancialAnalytics> analytics) {
        Map<String, List<BigDecimal>> trends = new HashMap<>();

        // 收集每个月的关键指标
        trends.put("currentRatio", analytics.stream()
                .map(CoolFinancialAnalytics::getCurrentRatio)
                .collect(Collectors.toList()));
        trends.put("grossMargin", analytics.stream()
                .map(CoolFinancialAnalytics::getGrossMargin)
                .collect(Collectors.toList()));
        trends.put("budgetExecutionRate", analytics.stream()
                .map(CoolFinancialAnalytics::getBudgetExecutionRate)
                .collect(Collectors.toList()));

        return trends;
    }

    private BigDecimal getMetricValue(CoolFinancialAnalytics analytics, String metricName) {
        return switch (metricName) {
            case "currentRatio" -> analytics.getCurrentRatio();
            case "quickRatio" -> analytics.getQuickRatio();
            case "grossMargin" -> analytics.getGrossMargin();
            case "netProfitMargin" -> analytics.getNetProfitMargin();
            case "returnOnEquity" -> analytics.getReturnOnEquity();
            case "budgetExecutionRate" -> analytics.getBudgetExecutionRate();
            default -> throw new CoolServiceException("未知的指标名称: " + metricName);
        };
    }

    private BigDecimal calculateAverage(List<BigDecimal> values) {
        if (values == null || values.isEmpty()) {
            return BigDecimal.ZERO;
        }
        return values.stream()
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(new BigDecimal(values.size()), 2, RoundingMode.HALF_UP);
    }

    private List<Long> getDepartmentIds() {
        // 这里应该从部门服务获取实际的部门ID列表
        // 示例返回一些测试数据
        return Arrays.asList(1L, 2L, 3L);
    }

    private void aggregateQuarterlyData(Integer fiscalYear, Integer fiscalQuarter) {
        // 实现季度数据汇总逻辑
        // 可以计算季度平均值或其他汇总指标
    }

    private void aggregateYearlyData(Integer fiscalYear) {
        // 实现年度数据汇总逻辑
        // 可以计算年度平均值或其他汇总指标
    }
}